package com.site.controller;

import com.site.domain.Result;
import com.site.domain.User;
import com.site.repository.UserRepository;
import com.site.service.UserService;
import com.site.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by shengquan.wu on 2018/6/5.
 */
@RestController
public class UserController {

    private final static Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @GetMapping(value = "/users")
    public List<User> userList(){
        log.info("in user list");

        return userRepository.findAll();
    }


//    @PostMapping(value = "/users")
//    public User userAdd(@RequestParam("name") String name,
//                        @RequestParam("age") Integer age) {
//
//        User user = new User();
//        user.setName(name);
//        user.setAge(age);
//        return userRepository.save(user);
//    }

    /**
     * 对于添加方法， 如果参数过多，可以采用如下方式来传递参数
     * public User userAdd(User user){
     *     user.setName(user.getName());
     *     user.setAge(user.getAge());
     *     return userRepository.save(user);
     * }
     *
     */

    /**
     * 添加验证
     * 使用@Valid和BindingResult
     */
    @PostMapping(value = "/users")
    public Result<User> userAdd(@Valid User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.error("mgs={}, args={}",msg, user);
            return ResultUtil.error(1, msg);
        }

        user.setName(user.getName());
        user.setAge(user.getAge());
        return ResultUtil.success(userRepository.save(user));
    }




    @GetMapping(value = "/users/{id}")
    public User userFindOne(@PathVariable Integer id) {
        log.info("find one11");
        return userRepository.findOne(id);
    }

    @PutMapping(value = "/users/{id}")
    public User userUpdate(@PathVariable Integer id,
                           @RequestParam("name") String name,
                           @RequestParam("age") Integer age){

        //TODO
        return null;
    }

    @GetMapping(value = "/users/age/{id}")
    public void getAge(@PathVariable Integer id) throws Exception {
        userService.getAge(id);
    }

}


